import { ApiActionType, SearchArticle, Suggestion } from "@/types/data"
import { RootThunkAction, SearchAction } from "@/types/store"
import request from "@/utils/request"
import { sethistory } from "@/utils/storagehistory"
import { Dispatch } from "react"

export const getsearch=(e:string):RootThunkAction=>{
    return async(dispatch:Dispatch<SearchAction>)=>{
        const res = await request.get<ApiActionType<{ options: Suggestion }>>(
            '/suggestion',
            {
              params: {
                q: e,
              },
            }
          )
          // console.log(res);
          dispatch({ type: 'search/suggestion', payload: res.data.data.options })
    }
}

export const getsearchhisotry =(history:string[]):RootThunkAction=>{
  return async(dispatch)=>{
    sethistory(history)
  dispatch({
    type:'search/history',
    payload:history
  })
  }
}

export const getclearhistory = ():SearchAction =>{
  return {
  type:'search/clear'
  }
}

export const getresultlist = (q:string ,page:number = 1, per_page:number = 10):RootThunkAction=>{
 return async(dispatch)=>{
  const res = await request.get<ApiActionType<{page:number, per_page:number, total_count:number, results: SearchArticle[]}>>('/search', {
    params: {
      q,
      page,
      per_page
    }
  })
  console.log(res,'res');
  dispatch({
    type:'search/result',
    payload:res.data.data.results
  })
 }

}